package com.ruoyi.web.controller.warning;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.warning.domain.dto.PropertyDTO;
import com.ruoyi.warning.domain.entity.Property;
import com.ruoyi.warning.domain.entity.PropertyServer;
import com.ruoyi.warning.domain.query.PropertyQuery;
import com.ruoyi.warning.domain.vo.PropertyVO;
import com.ruoyi.warning.mapper.PropertyMapper;
import com.ruoyi.warning.service.IDevicesService;
import com.ruoyi.warning.service.IPropertyServerService;
import com.ruoyi.warning.service.IPropertyService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.ParseException;
import java.util.List;

/**
 * <p>
 * 资产表 前端控制器
 * </p>
 *
 * @author chenhc
 * @since 2025-05-14
 */
@RestController
@RequestMapping("/property")
@Api(tags = "资产", description = "用于处理资产相关操作的控制器")
public class PropertyController {
    @Resource
    private IPropertyService iPropertyService;
    @Resource
    private IPropertyServerService serverService;
    @Resource
    private PropertyMapper propertyMapper;
    @Resource
    private IDevicesService devicesService;

    @ApiOperation("资产分页")
    @Anonymous
    //@PreAuthorize("@ss.hasPermi('system:config:export')")
    @GetMapping(value = "/page")
    public R<TableDataInfo> page(PropertyQuery query)
    {
        return R.ok(iPropertyService.getPage(query));
    }

    @ApiOperation("资产详细")
    //@PreAuthorize("@ss.hasPermi('system:config:export')")
    @GetMapping(value = "/detail/{hostname}")
    public R detail(@PathVariable String hostname)
    {
        LambdaQueryWrapper<Property> wrapper = new QueryWrapper<Property>().lambda()
                .eq(Property::getHostname, hostname);
        Property property = iPropertyService.getOne(wrapper);
        PropertyVO propertyVO = new PropertyVO();
        if("服务器".equals(property.getDeviceType())){
            LambdaQueryWrapper<PropertyServer> serverWrapper = new QueryWrapper<PropertyServer>().lambda()
                    .eq(PropertyServer::getPropertyId, property.getPropertyId());
            PropertyServer propertyServer = serverService.getOne(serverWrapper);
            if(ObjectUtils.isNotEmpty(propertyServer)){
                BeanUtils.copyProperties(propertyServer, propertyVO);
            }
        }
        BeanUtils.copyProperties(property, propertyVO);
        return R.ok(propertyVO);
    }

    @ApiOperation("新增或修改资产")
    //@PreAuthorize("@ss.hasPermi('system:config:export')")
    @PostMapping(value = "/saveOrUpdate")
    public R saveOrUpdate(@RequestBody PropertyDTO propertyDTO)
    {
        Property property = new Property();
        if(propertyDTO.getHostname() == null || propertyDTO.getHostname().isEmpty()) {
            return R.fail("ip为空");
        }
        // 去除ip中的空格
        propertyDTO.setHostname(propertyDTO.getHostname().replaceAll("\\s", ""));
        String ipPattern = "^((25[0-5]|2[0-4]\\d|[01]?\\d\\d?)\\.){3}(25[0-5]|2[0-4]\\d|[01]?\\d\\d?)$";
        if(!propertyDTO.getHostname().matches(ipPattern)){
            return R.fail("请输入正确的ip");
        }
        BeanUtils.copyProperties(propertyDTO, property);
        List<Property> list = iPropertyService.list(new LambdaQueryWrapper<Property>()
                .eq(Property::getHostname, property.getHostname()));
        if(list.size()>0){
            property.setPropertyId(list.get(0).getPropertyId());
        }
//        if(ObjectUtils.isEmpty(property.getPropertyId())&&list.size()>0){
//            return R.fail("资产已存在");
//        }
        iPropertyService.saveOrUpdate(property);
//        property = iPropertyService.getOne(new LambdaQueryWrapper<Property>()
//               .eq(Property::getHostname, property.getHostname()));
        if("服务器".equals(property.getDeviceType())){
            PropertyServer propertyServer = new PropertyServer();
            BeanUtils.copyProperties(propertyDTO, propertyServer);
            list = iPropertyService.list(new LambdaQueryWrapper<Property>()
                    .eq(Property::getHostname, property.getHostname()));
            property.setPropertyId(list.get(0).getPropertyId());
//            propertyServer.setPropertyId(property.getPropertyId());
            serverService.saveOrUpdate(propertyServer);
        }
        return R.ok();
    }

    @ApiOperation("删除资产")
    //@PreAuthorize("@ss.hasPermi('system:config:export')")
    @PostMapping(value = "/delete")
    public R delete(@RequestBody List<String> ids)
    {
        return R.ok(iPropertyService.removeByIds(ids));
    }

    @ApiOperation("导入资产excel")
    @Anonymous
    //@PreAuthorize("@ss.hasPermi('system:config:export')")
    @PostMapping(value = "/importExcel")
    public R importExcel(MultipartFile file) throws IOException, ParseException {
        iPropertyService.importExcel(file);
        return R.ok();
    }

//    @ApiOperation("导出资产excel")
    //@PreAuthorize("@ss.hasPermi('system:config:export')")
    @PostMapping(value = "/exportExcel", consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
    public void exportExcel(@ModelAttribute PropertyQuery query, HttpServletResponse response) throws IOException {
//        List<Property> list = iPropertyService.list(new QueryWrapper<Property>().lambda()
//                .eq(query.getType()!=null,Property::getDeviceType,query.getType()));
        List<PropertyVO> list = propertyMapper.getList(query);
        ExcelUtil<PropertyVO> util = new ExcelUtil<PropertyVO>(PropertyVO.class);
        util.exportExcel(response, list, "资产表");
    }

    @ApiOperation("获取资产的设备类型")
    @Anonymous
    //@PreAuthorize("@ss.hasPermi('system:config:export')")
    @GetMapping(value = "/getDeviceType")
    public R getDeviceType()
    {
        List<Property> typeList = iPropertyService.list(new LambdaQueryWrapper<Property>().isNotNull(Property::getDeviceType).groupBy(Property::getDeviceType));
        List<String> deviceType = typeList.stream().map(Property::getDeviceType).toList();
        return R.ok(deviceType);
    }

    @ApiOperation("获取资产的厂区")
    @Anonymous
    //@PreAuthorize("@ss.hasPermi('system:config:export')")
    @GetMapping(value = "/getDeviceArea")
    public R getDeviceArea()
    {
        List<Property> areaList = iPropertyService.list(new LambdaQueryWrapper<Property>()
                .isNotNull(Property::getArea)
                .ne(Property::getArea, "")
                .groupBy(Property::getArea));
        List<String> deviceArea = areaList.stream().map(Property::getArea).toList();
        return R.ok(deviceArea);
    }

    @ApiOperation("资产采集")
    //@PreAuthorize("@ss.hasPermi('system:config:export')")
    @PostMapping(value = "/collect")
    public R collect(@RequestBody List<PropertyDTO> list)
    {
        for(PropertyDTO propertyDTO:list){
            iPropertyService.collect(propertyDTO);
            devicesService.addDevice(propertyDTO.getDeviceId());
        }
        return R.ok();
    }

    public static void main(String[] args) {
        String ip = "192.168.1.1";
        String ipPattern = "^((25[0-5]|2[0-4]\\d|[01]?\\d\\d?)\\.){3}(25[0-5]|2[0-4]\\d|[01]?\\d\\d?)$";
        if(!ip.matches(ipPattern)){
            System.out.println("请输入正确的ip");
        }else System.out.println("正确");
    }
}
